package ace.cmp.util.lambda;

import java.lang.invoke.SerializedLambda;
import java.lang.reflect.Method;
import lombok.*;
import org.apache.commons.text.WordUtils;

/**
 * @author caspar
 * @date 2024/6/27 16:50
 */
public final class SerializedLambdaUtils {
  @SneakyThrows
  public static <T> SerializedLambdaMethod getMethod(SFunction<T, Object> sFn) {
    // 直接调用writeReplace
    Method writeReplace = sFn.getClass().getDeclaredMethod("writeReplace");
    writeReplace.setAccessible(true);
    Object sl = writeReplace.invoke(sFn);
    SerializedLambda serializedLambda = (SerializedLambda) sl;
    String methodName = serializedLambda.getImplMethodName();
    String fieldName = WordUtils.uncapitalize(methodName.replace("get", ""));
    return SerializedLambdaMethod.builder()
        .methodName(serializedLambda.getImplMethodName())
        .fieldName(fieldName)
        .build();
  }

  @Data
  @NoArgsConstructor
  @AllArgsConstructor
  @Builder
  public static class SerializedLambdaMethod {
    private String methodName;
    private String fieldName;
  }
}
